//
//  ViewController.m
//  CoreData
//
//  Created by 郭明皓 on 15/11/20.
//  Copyright © 2015年 郭明皓工作室. All rights reserved.
//

#import "ViewController.h"
#import "CoreDataManager.h"
#import "Student.h"
@interface ViewController ()

@property (nonatomic, strong)CoreDataManager *manager;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.manager = [CoreDataManager defaults];
    
    NSLog(@"%@", self.manager.applicationDocumentsDirectory);
    [self.manager applicationDocumentsDirectory];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//删除
- (IBAction)delete:(id)sender {
    
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"sex", @"%@"], @"?"];
    request.predicate = predicate;
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
    
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error;
    NSArray *arry = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    
    for (Student *stu in arry) {
        [self.manager.managedObjectContext deleteObject:stu];
    }
    [self.manager saveContext];
    
    
}
//更新
- (IBAction)update:(id)sender {
}
//查找
- (IBAction)select:(id)sender {
    //1.获取查询数据的请求,相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
    //2. 添加约束 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], @"成精"];//搜索名字为成精的名字
    request.predicate = predicate;
    
    //通过某个key给数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
    
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error;
    NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    NSLog(@"%ld", array.count);
    
    Student *stu = [array lastObject];
    stu.sex = @"好像大概应该差不多可能约么也许是个女的把,你个傻逼";
    
    [self.manager saveContext];

}

- (IBAction)Add:(id)sender {
    // 创建实体描述
    // 参数1:描述的实体
    // 参数2:数据管理器
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.manager.managedObjectContext];
    
    Student *stu = [[Student alloc]initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
    stu.name = @"成精";
    stu.age = @13;
    stu.sex = @"?";
    stu.hobby = @"吹🐂逼";
    stu.number = @213;
    
    [self.manager saveContext];
}
@end
